package cn.devcat.sso.util;

import java.util.Arrays;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson2.JSONObject;

/**
 * Redis 工具类
 * @author huhailong
 *
 */
@Component
public class RedisUtil {

	@Autowired
	RedisTemplate<String, String> redisTemplate;

	/**
	 *
	 * @param key			缓存内容key
	 * @param expireTime	过期时间，如果为-1表示永远不过期,以秒为单位
	 * @param o				缓存内容
	 */
	public void insertOfJson(String key, Object o, long expireTime) {
		redisTemplate.opsForValue().set(key, JSONObject.toJSONString(o));
		if(expireTime > -1) {
			redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
		}
	}

	/**
	 * 存储字符串值
	 * @param key
	 * @param o
	 * @param expireTime
	 */
	public void insertOfString(String key, String o, long expireTime) {
		redisTemplate.opsForValue().set(key, o);
		if(expireTime > -1) {
			redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
		}
	}

	/**
	 * 删除指定key的缓存
	 * @param keys 缓存的key数组
	 */
	public void delete(String...keys) {
		redisTemplate.delete(Arrays.asList(keys));
	}

	/**
	 * 获取指定类型的缓存
	 * @param <T>
	 * @param key
	 * @param clazz
	 * @return
	 */
	public <T> T select(String key, Class<T> clazz){
		String jsonStr = redisTemplate.opsForValue().get(key);
		return JSONObject.parseObject(jsonStr, clazz);
	}

	/**
	 * 获取原生的缓存json字符串
	 * @param key
	 * @return
	 */
	public String select(String key) {
		return redisTemplate.opsForValue().get(key);
	}

	/**
	 * 检查key是否存在
	 * @param key
	 * @return
	 */
	public boolean checkKey(String key) {
		if(key == null) {
			return false;
		}
		return redisTemplate.hasKey(key);
	}

  public void clearCache(){
    Set<String> keys1 = redisTemplate.keys("roleListByApiPatternId:" + "*");
    Set<String> keys2 = redisTemplate.keys("roleListByUserId:" + "*");
    Set<String> keys3 = redisTemplate.keys("apiPatternList:" + "*");

    redisTemplate.delete(keys1);
    redisTemplate.delete(keys2);
    redisTemplate.delete(keys3);
  }

}
